package com.liruo.demo.serialize.jackson.factory;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.liruo.demo.serialize.jackson.model.User;
import java.io.IOException;

/**
 * @Author:liruo
 * @Date:2023-02-20-02:38:43
 * @Desc
 */
public class MySerializerFactory extends JsonSerializer<User> implements ContextualSerializer {

  private String prefix;
  private Class clazz;

  public MySerializerFactory() {
  }

  public MySerializerFactory(String prefix, Class clazz) {
    this.prefix = prefix;
    this.clazz = clazz;
  }

  @Override
  public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property)
      throws JsonMappingException {
    String prefix = property.getAnnotation(ValuePrefix.class).prefix();
    JavaType type = property.getType();

    if (type.isTypeOrSubTypeOf(User.class)) {
      return new MySerializerFactory(prefix, User.class);
    }

    throw new RuntimeException("不支持的类型,  仅支持 String, Collection");
  }

  @Override
  public void serialize(User user, JsonGenerator jsonGenerator,
      SerializerProvider serializerProvider) throws IOException {
    if (user == null) {
      serializerProvider.defaultSerializeNull(jsonGenerator);
      return;
    }
    jsonGenerator.writeStartObject();
    jsonGenerator.writeStringField("name", MySerializerFactory.this.prefix + user.getName());
    jsonGenerator.writeStringField("des", MySerializerFactory.this.prefix + user.getName());
    jsonGenerator.writeEndObject();
  }

  @Override
  public Class<User> handledType() {
    return clazz;
  }
}
